package com.sharecode.stock.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import com.sharecode.stock.vo.MailBean;
import com.sharecode.stock.vo.NoticeEmail;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MailService {
	@Autowired
	private JavaMailSender javaMailSender;
	@Autowired
	private NoticeEmailService noticeEmailService;
	@Value("${spring.mail.username}")
	private String mailSender; // 邮件发送者

	public void sendSimpleMail(MailBean mailBean) {
		try {
			SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
			// 邮件发送人
			simpleMailMessage.setFrom(mailSender);
			// 邮件接收人
			simpleMailMessage.setTo(mailBean.getRecipient());
			// 邮件主题
			simpleMailMessage.setSubject(mailBean.getSubject());
			// 邮件内容
			simpleMailMessage.setText(mailBean.getContent());
			if (mailBean.isBcc()) {
				List<NoticeEmail> notices = noticeEmailService.findAllSend();
				if (CollectionUtils.isNotEmpty(notices)) {
					List<String> bcc = new ArrayList<String>();
					for (int i = 0; i < notices.size(); i++) {
						String email = notices.get(i).getEmail();
						if (StringUtils.isNotBlank(email)) {
							bcc.add(email);
						}
					}
					if (CollectionUtils.isNotEmpty(bcc)) {
						simpleMailMessage.setBcc(bcc.toArray(new String[bcc.size()]));
					}
				}
			}
			javaMailSender.send(simpleMailMessage);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("邮件发送失败", e.getMessage());
		}
	}
}
